package com.mall.shopping.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.shopping.IProductService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.PanelContentConverter;
import com.mall.shopping.converter.PanelConverter;
import com.mall.shopping.converter.ProductConverter;
import com.mall.shopping.converter.ProductDetailConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContent;
import com.mall.shopping.dal.entitys.ItemDesc;
import com.mall.shopping.dal.persistence.ItemDescMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author yfsper233
 * @time 2021/7/20-23:04
 */
@Slf4j
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ProductDetailConverter productDetailConverter;
    @Autowired
    private ProductConverter productConverter;
    @Autowired
    private PanelMapper panelMapper;
    @Autowired
    private PanelContentMapper panelContentMapper;
    @Autowired
    private PanelConverter panelConverter;
    @Autowired
    private PanelContentConverter panelContentConverter;
    @Autowired
    private ItemDescMapper itemDescMapper;


    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();

        try {
            request.requestCheck();

            Item item = itemMapper.selectByPrimaryKey(request.getId());
            ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(request.getId());
            ProductDetailDto productDetailDto = productDetailConverter.item2Dto(item);

            productDetailDto.setDetail(itemDesc.getItemDesc());
            String[] images = item.getImages();
            List<String> stringList = Arrays.asList(images);
            if (stringList.size() > 0) {
                productDetailDto.setProductImageBig(stringList.get(0));
                productDetailDto.setProductImageSmall(stringList);
            }
            productDetailResponse.setProductDetailDto(productDetailDto);
//            productDetailResponse.setCode(ShoppingRetCode.SHOPPING_HOMEPAGE.getCode());
//            productDetailResponse.setMsg(ShoppingRetCode.SHOPPING_HOMEPAGE.getMessage());
            productDetailResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return productDetailResponse;

        } catch (ValidateException v) {
            v.printStackTrace();
            productDetailResponse.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            productDetailResponse.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return productDetailResponse;
    }


    /**
     * @author hdf
     * @description 分页查询所有商品
     * @param request
     * @return
     */
    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        AllProductResponse response = new AllProductResponse();

        try{
            //请求参数检验
            request.requestCheck();

            //根据请求参数实现分页
            PageHelper.startPage(request.getPage(),request.getSize());


            //使用TK-Mapper查询数据库，获得DAO层对象
            Example example = new Example(Item.class);
            List<Item> items = null;

            //无排序情况
            if (request.getSort() == null){
            //用户只输入最低价格
            if (request.getPriceGt() != null && request.getPriceLte() == null){

                    Example.Criteria criteria = example.createCriteria();
                    criteria.andGreaterThanOrEqualTo("price",request.getPriceGt());
                    items = itemMapper.selectByExample(example);

            }
            //用户只输入最高价格
            else if (request.getPriceLte() != null && request.getPriceGt() == null){

                    Example.Criteria criteria = example.createCriteria();
                    criteria.andLessThanOrEqualTo("price",request.getPriceLte());
                    items = itemMapper.selectByExample(example);

            }

            //用户最高价格和最低价格都输入了
            else if (request.getPriceGt() != null && request.getPriceLte() != null){

                    Example.Criteria criteria = example.createCriteria();
                    criteria.andGreaterThanOrEqualTo("price",request.getPriceGt());
                    criteria.andLessThanOrEqualTo("price",request.getPriceLte());
                    items = itemMapper.selectByExample(example);

            } else {
               items = itemMapper.selectAll();
            }
            }
            //有排序情况
            else {

                if ("1".equals(request.getSort())){
                    example.setOrderByClause("price asc");
                } else if ("-1".equals(request.getSort())){
                    example.setOrderByClause("price desc");
                }

                //用户只输入最低价格
                if (request.getPriceGt() != null && request.getPriceLte() == null){



                        Example.Criteria criteria = example.createCriteria();
                        criteria.andGreaterThanOrEqualTo("price",request.getPriceGt());
                        items = itemMapper.selectByExample(example);

                }
                //用户只输入最高价格
                else if (request.getPriceLte() != null && request.getPriceGt() == null){

                        Example.Criteria criteria = example.createCriteria();
                        criteria.andLessThanOrEqualTo("price",request.getPriceLte());
                        items = itemMapper.selectByExample(example);

                }

                //用户最高价格和最低价格都输入了
                else if (request.getPriceGt() != null && request.getPriceLte() != null){

                        Example.Criteria criteria = example.createCriteria();
                        criteria.andGreaterThanOrEqualTo("price",request.getPriceGt());
                        criteria.andLessThanOrEqualTo("price",request.getPriceLte());
                        items = itemMapper.selectByExample(example);

                } else {
                    items = itemMapper.selectByExample(example);
                }
            }


            //使用mapstruct对象映射工具，获得数据传输对象
            List<ProductDto> productDtos = productConverter.items2Dto(items);

            //封装response
            response.setProductDtoList(productDtos);
            PageInfo<Item> objectPageInfo = new PageInfo<>(items);
            long total = objectPageInfo.getTotal();
            response.setTotal(total);

            //通过response继承的AbstractResponse的方法封装
            // code: 200
            // message: "success"
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return response;
        }

        catch (ValidateException e){
            response.setCode(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getCode());
            response.setMsg(ShoppingRetCode.PARAMETER_VALIDATION_FAILED.getMessage());
        }
        catch (Exception e){
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
        }

        return response;
    }

    /**
     * @author hdf
     * @description 热门推荐/固定
     * @return
     */
    @Override
    public RecommendResponse getRecommendGoods() {

        RecommendResponse recommendResponse = new RecommendResponse();
        Example example = new Example(Panel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name","热门推荐");
        List<Panel> panels = panelMapper.selectByExample(example);
        Set<PanelDto> panelDtos = panelConverter.panelstoDtos(panels);
        for (PanelDto panelDto : panelDtos) {
            Example example1 = new Example(PanelContent.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("panelId",panelDto.getId());
            List<PanelContent> panelContents = panelContentMapper.selectByExample(example1);
            List<PanelContentItemDto> panelContentItemDtos = panelContentConverter.panelContentToDos(panelContents);

            //查询商品信息
            for (PanelContentItemDto panelContentItemDto : panelContentItemDtos) {
                Item item = itemMapper.selectByPrimaryKey(panelContentItemDto.getProductId());
                panelContentItemDto.setProductName(item.getTitle());
                panelContentItemDto.setSalePrice(item.getPrice());
                panelContentItemDto.setSubTitle(item.getSellPoint());
            }

            panelDto.setPanelContentItems(panelContentItemDtos);
            recommendResponse.setPanelContentItemDtos(panelDtos);
        }
        recommendResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        recommendResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return recommendResponse;

    }
}
